package com.example.web.servlet;

import com.example.common.Result;
import com.example.model.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admitLogin")
public class AdmitLoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 验证码
        String check = req.getParameter("check");
        HttpSession session = req.getSession();
        String check_server = (String) session.getAttribute("CHECKCODE_SERVER");
        if (StringUtils.isEmpty(check) || !check_server.equalsIgnoreCase(check)) {
            Result result = Result.fail(400, "验证码填写错误");

            String result_str = objectMapper.writeValueAsString(result);
            System.out.println(result_str);
            resp.getWriter().write(result_str);
            return;
        }
        // 获取用户发送的信息 , 判断用户信息是否正确
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 用户信息填写错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ) {
            Result result = Result.fail(400, "请正确填写登录信息");
            String result_str = objectMapper.writeValueAsString(result);
            System.out.println(result_str);
            resp.getWriter().write(result_str);
            return;
        }
        Result result = null;
        if ("root".equalsIgnoreCase(username) && "root".equalsIgnoreCase(password)) {
            result = Result.success("登录成功");
        } else {
            result = Result.fail(400, "账号或密码错误");
        }
        String result_str = objectMapper.writeValueAsString(result);
        resp.getWriter().write(result_str);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
